from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.work_order import WorkOrder, WorkOrderFieldValue, WorkOrderField
from app.models.user import User
from app.models.area import Area
from app.models.process_record import ProcessRecord
from app.models.material import MaterialUsage
from app.models import db
from .work_orders_utils import (
    get_current_user, handle_db_error, 
    parse_datetime, apply_user_filter, validate_work_order_permission
)
from app.utils.auth import require_permission
import json
import uuid
from datetime import datetime

work_orders_core_bp = Blueprint('work_orders_core', __name__)

@work_orders_core_bp.route('', methods=['GET'])
@require_permission('work_order.view', 'work_order.view_all')
def get_work_orders():
    """获取工单列表"""
    try:
        current_user = get_current_user()
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = min(request.args.get('per_page', 10, type=int), 100)
        status = request.args.get('status')
        priority = request.args.get('priority')
        assignee_id = request.args.get('assignee_id', type=int)
        creator_id = request.args.get('creator_id', type=int)
        area_id = request.args.get('area_id', type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        search = request.args.get('search')
        
        # 获取区域过滤参数，默认为True
        area_filter_str = request.args.get('area_filter', 'true')
        area_filter = area_filter_str.lower() in ['true', '1', 'yes']
        
        # 获取show_all参数，用于管理员查看所有工单
        show_all_str = request.args.get('show_all', 'false')
        show_all = show_all_str.lower() in ['true', '1', 'yes']
        
        # 构建基础查询
        query = WorkOrder.query
        
        # 如果是管理员且设置了show_all参数，则跳过权限过滤
        if current_user.role == 'admin' and show_all:
            # 管理员查看所有工单，不应用用户权限过滤
            pass
        else:
            # 应用用户权限过滤，传入area_filter和status参数
            query = apply_user_filter(query, current_user, area_filter, status)
        
        # 应用过滤条件
        if status:
            # 支持多状态过滤，用逗号分隔
            if ',' in status:
                status_list = [s.strip() for s in status.split(',')]
                query = query.filter(WorkOrder.status.in_(status_list))
            else:
                query = query.filter(WorkOrder.status == status)
        if priority:
            query = query.filter(WorkOrder.priority == priority)
        if assignee_id:
            query = query.filter(WorkOrder.assignee_id == assignee_id)
        if creator_id:
            query = query.filter(WorkOrder.creator_id == creator_id)
        if area_id:
            query = query.filter(WorkOrder.area_id == area_id)
        
        # 日期范围过滤
        if start_date:
            start_dt = parse_datetime(start_date)
            query = query.filter(WorkOrder.created_at >= start_dt)
        if end_date:
            end_dt = parse_datetime(end_date)
            query = query.filter(WorkOrder.created_at <= end_dt)
        
        # 搜索过滤
        if search:
            search_pattern = f"%{search}%"
            query = query.filter(
                db.or_(
                    WorkOrder.title.ilike(search_pattern),
                    WorkOrder.description.ilike(search_pattern),
                    WorkOrder.work_order_number.ilike(search_pattern)
                )
            )
        
        # 排序
        query = query.order_by(WorkOrder.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        work_orders_list = []
        for work_order in pagination.items:
            # 包含自定义字段数据
            work_order_dict = work_order.to_dict(include_custom_fields=True)
            
            # 添加创建者信息
            if work_order.creator:
                work_order_dict['creator'] = {
                    'id': work_order.creator.id,
                    'username': work_order.creator.username,
                    'name': work_order.creator.name
                }
            
            # 添加分配者信息
            if work_order.assignee:
                work_order_dict['assignee'] = {
                    'id': work_order.assignee.id,
                    'username': work_order.assignee.username,
                    'name': work_order.assignee.name
                }
            
            # 添加区域信息
            if work_order.area:
                work_order_dict['area'] = {
                    'id': work_order.area.id,
                    'name': work_order.area.name
                }
            
            work_orders_list.append(work_order_dict)
        
        return jsonify({
            'work_orders': work_orders_list,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_core_bp.route('', methods=['POST'])
@require_permission('work_order.create')
@handle_db_error("创建工单")
def create_work_order():
    """创建工单"""
    current_user = get_current_user()
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '未收到请求数据'}), 400
    
    # 验证必填字段
    required_fields = ['description', 'area_id']
    for field in required_fields:
        if not data.get(field):
            field_name = '描述' if field == 'description' else '区域'
            return jsonify({'error': f'{field_name} 不能为空'}), 400
    
    # 生成工单号
    work_order_number = f"WO{datetime.now().strftime('%Y%m%d')}{str(uuid.uuid4())[:8].upper()}"
    
    # 创建工单
    work_order = WorkOrder(
        order_number=work_order_number,
        title=data.get('title'),  # title现在是可选字段
        description=data['description'],
        priority=data.get('priority', 'medium'),
        status=data.get('status', 'pending'),
        creator_id=current_user.id,
        assignee_id=data.get('assignee_id'),
        area_id=data['area_id'],  # area_id现在是必填字段
        group_id=current_user.group_id
    )
    
    db.session.add(work_order)
    db.session.flush()  # 获取工单ID
    
    # 处理自定义字段
    custom_fields = data.get('custom_fields', {})
    if custom_fields:
        for field_name, field_value in custom_fields.items():
            if field_value is not None and field_value != '':
                # 查找字段定义
                field_def = WorkOrderField.query.filter_by(name=field_name).first()
                if field_def:
                    field_value_obj = WorkOrderFieldValue(
                        work_order_id=work_order.id,
                        field_id=field_def.id,
                        value=str(field_value)
                    )
                    db.session.add(field_value_obj)
    
    db.session.commit()
    
    return jsonify({
        'work_order': work_order.to_dict(),
        'message': '工单创建成功'
    }), 201

@work_orders_core_bp.route('/<int:work_order_id>', methods=['GET'])
@require_permission('work_order.view')
def get_work_order(work_order_id):
    """获取工单详情"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(work_order_id)
        
        # 权限检查
        if not validate_work_order_permission(work_order, current_user, "view"):
            return jsonify({'error': '权限不足'}), 403
        
        # 获取工单详情（包含自定义字段）
        work_order_dict = work_order.to_dict(include_custom_fields=True)
        
        # 添加关联信息
        if work_order.creator:
            work_order_dict['creator'] = work_order.creator.to_dict()
        if work_order.assignee:
            work_order_dict['assignee'] = work_order.assignee.to_dict()
        if work_order.area:
            work_order_dict['area'] = work_order.area.to_dict()
        
        return jsonify({'work_order': work_order_dict}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_core_bp.route('/<int:work_order_id>', methods=['PUT'])
@require_permission('work_order.edit')
@handle_db_error("更新工单")
def update_work_order(work_order_id):
    """更新工单"""
    current_user = get_current_user()
    work_order = WorkOrder.query.get_or_404(work_order_id)
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '未收到请求数据'}), 400
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "update"):
        return jsonify({'error': '权限不足'}), 403
    
    # 更新基本字段
    updatable_fields = ['title', 'description', 'priority', 'status', 'assignee_id', 'area_id']
    for field in updatable_fields:
        if field in data:
            setattr(work_order, field, data[field])
    
    # 处理日期字段
    if 'due_date' in data:
        work_order.due_date = parse_datetime(data['due_date']) if data['due_date'] else None
    
    # 更新自定义字段
    if 'custom_fields' in data:
        # 删除现有的自定义字段值
        WorkOrderFieldValue.query.filter_by(work_order_id=work_order.id).delete()
        
        # 添加新的自定义字段值
        for field_name, field_value in data['custom_fields'].items():
            if field_value is not None and field_value != '':
                field_def = WorkOrderField.query.filter_by(name=field_name).first()
                if field_def:
                    field_value_obj = WorkOrderFieldValue(
                        work_order_id=work_order.id,
                        field_id=field_def.id,
                        value=str(field_value)
                    )
                    db.session.add(field_value_obj)
    
    work_order.updated_at = datetime.utcnow()
    db.session.commit()
    
    return jsonify({
        'work_order': work_order.to_dict(),
        'message': '工单更新成功'
    }), 200

@work_orders_core_bp.route('/<int:work_order_id>', methods=['DELETE'])
@require_permission('work_order.delete')
@handle_db_error("删除工单")
def delete_work_order(work_order_id):
    """删除工单"""
    current_user = get_current_user()
    work_order = WorkOrder.query.get_or_404(work_order_id)
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "delete"):
        return jsonify({'error': '权限不足'}), 403
    
    # 删除相关记录
    WorkOrderFieldValue.query.filter_by(work_order_id=work_order.id).delete()
    ProcessRecord.query.filter_by(work_order_id=work_order.id).delete()
    MaterialUsage.query.filter_by(work_order_id=work_order.id).delete()
    
    # 删除工单
    db.session.delete(work_order)
    db.session.commit()
    
    return jsonify({'message': '工单删除成功'}), 200